package pers.warren.ai.oneapi.httpclient;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class HttpClientImpl implements HttpClient{

    private final OkHttpClient okHttpClient;


    @Value("warren.http.client.response.headers")
    private List<String> responseHeaders;
    @Override
    public <R> Response<R> post(String url, Map<String, String> param, Map<String,String> header , Class<R> clz, String json) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");//数据类型为json格式
        RequestBody body = RequestBody.create(JSON,json);
        Request request = createRequestBuilder(header)
                .url(appendParamsToUrl(url,param))
                .post(body)
                .build();
        try {
            okhttp3.Response response = okHttpClient.newCall(request).execute();
            String responseStr = response.body().string();
            R responseBody = JSONUtil.toBean(responseStr, clz);
            Map<String,List<String>> headerMap = new HashMap<>();
            for (String responseHeader : responseHeaders) {
                headerMap.put(responseHeader,response.headers(responseHeader));
            }
            return new Response<R>().setResponseBody(responseBody).setHeader(headerMap);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    private Request.Builder addHeader(Request.Builder builder, Map<String, String> headers) {
        headers.forEach(builder::addHeader);
        return builder;
    }


    private Request.Builder createRequestBuilder(Map<String, String> headers) {
        return  addHeader(new Request.Builder(),headers);
    }






    private String appendParamsToUrl(String url, Map<String, String> param) {
        StringBuilder stringBuilder = new StringBuilder(url);
        if (!url.contains("?")) {
            stringBuilder.append("?");
        } else if (!url.endsWith("&")) {
            stringBuilder.append("&");
        }

        for (Map.Entry<String, String> entry : param.entrySet()) {
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }

        // 去除末尾多余的 '&'
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return stringBuilder.toString();
    }

    @Override
    public <R> Response<R> get(String url, Map<String, String> param) {
        Request request = new Request.Builder()
                .url(appendParamsToUrl(url,param))
                .get()
                .build();
        return null;
    }
}
